#!/usr/bin/env bash
CUR_PATH=$(cd "$(dirname "$0")"; pwd)

SHELL_FILE_1=transform_0200_0f37.sh
SHELL_FILE_2=delete_all.sh
SHELL_FILE_3=transform_0f38_0f39.sh

# 要定时执行的任务
TASK_COMMAND_1="flock -xn /tmp/parquet_0200_transformer.lock $CUR_PATH/$SHELL_FILE_1 &"
# 要添加的crontab任务
CRONTAB_TASK_1="*/10 * * * * ${TASK_COMMAND_1}"

# 要定时执行的任务
TASK_COMMAND_2="flock -xn /tmp/parquet_delete_transformer.lock $CUR_PATH/$SHELL_FILE_2 &"
# 要添加的crontab任务
CRONTAB_TASK_2="*/40 * * * * ${TASK_COMMAND_2}"

# 要定时执行的任务
TASK_COMMAND_3="flock -xn /tmp/parquet_0f38_transformer.lock $CUR_PATH/$SHELL_FILE_3 &"
# 要添加的crontab任务
CRONTAB_TASK_3="*/50 * * * * ${TASK_COMMAND_3}"


# 备份原始crontab记录文件
CRONTAB_BAK_FILE="${CUR_PATH}/crontab_bak"

# 创建crontab任务函数
function create_crontab()
{
    echo 'Create crontab task...'
    crontab -l > ${CRONTAB_BAK_FILE} 2>/dev/null
    sed -i "/.*$SHELL_FILE_1/d" ${CRONTAB_BAK_FILE}  # 已存在任务时会被sed删除，防止重复添加
    sed -i "/.*$SHELL_FILE_2/d" ${CRONTAB_BAK_FILE}  # 已存在任务时会被sed删除，防止重复添加
    sed -i "/.*$SHELL_FILE_3/d" ${CRONTAB_BAK_FILE}  # 已存在任务时会被sed删除，防止重复添加
    echo "${CRONTAB_TASK_1}" >> ${CRONTAB_BAK_FILE}
    echo "${CRONTAB_TASK_2}" >> ${CRONTAB_BAK_FILE}
    echo "${CRONTAB_TASK_3}" >> ${CRONTAB_BAK_FILE}
    crontab ${CRONTAB_BAK_FILE}
    echo 'Complete'
}

# 清除crontab任务函数
function clear_crontab(){
    echo 'Delete crontab task...'
    crontab -l > ${CRONTAB_BAK_FILE} 2>/dev/null
    sed -i "/.*${SCRIPT_NAME}/d" ${CRONTAB_BAK_FILE}
    crontab ${CRONTAB_BAK_FILE}

    echo 'Complete'
}

if [ $# -lt 1 ]; then
    echo "Usage: $0 [start | stop]"
    exit 1
fi

case $1 in
    'start' )
        create_crontab
        ;;
    'stop' )
        clear_crontab
        ;;
esac
